<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/5
 * Time: 13:55
 */
//获取微信服务器IP地址access_token
function getWxToken(){
    $time = Storage::lastModified('token.json'); //获取文件最后一次被修改的时间
    if(time() < $time+7200){
        $token = Storage::get('token.json');
    }else{
        $token = GoCurl('https://api.weixin.qq.com/cgi-bin/token','GET',array('grant_type'=>'client_credential','appid'=>getenv('WECHAT_APPID'),'secret'=>getenv('WECHAT_SECRET')));
        Storage::put('token.json', $token); //缓存数据
    }
    return $token;
}
//获取微信服务器IP地址
function getWxIp(){
    $token    = getWxToken();
    $tokenarr = json_decode($token,true);
    $ipjson   = GoCurl('https://api.weixin.qq.com/cgi-bin/getcallbackip','GET',array('access_token'=>$tokenarr['access_token']));
    $iparr    = json_decode($ipjson,true);
    $ip       = $_SERVER['SERVER_ADDR'];
    if(in_array($ip,$iparr)){
        return true;
    }else{
        return false;
    }
}
//获取微信签名
function getWxSign(){
    $time = Storage::lastModified('sign.json'); //获取文件最后一次被修改的时间
    if(time() < $time+7200){
        $signjson = Storage::get('sign.json');
    }else {
        $token = getWxToken();
        $tokenarr = json_decode($token, true);
        $signjson = GoCurl('https://api.weixin.qq.com/cgi-bin/ticket/getticket', 'GET', array('access_token' => $tokenarr['access_token'], 'type' => 'jsapi'));
        Storage::put('sign.json', $signjson); //缓存数据
    }
    return $signjson;
}
//获取微信配置信息
function getWxConfig(){
    $arr              = [];
    $signarr          = json_decode(getWxSign(),true);
    $arr['nonceStr']  = getRandomStr(16);
    $arr['timestamp'] = time();
    $ticket           = $signarr['ticket'];
    $protocol         = (!empty($_SERVER ['HTTPS']) && $_SERVER ['HTTPS'] !== 'off' || $_SERVER ['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url              = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $arr['signature'] = sha1("jsapi_ticket=$ticket&noncestr=".$arr['nonceStr']."&timestamp=".$arr['timestamp']."&url=".$url);
    $arr['appId']     = getenv('WECHAT_APPID');
    return $arr;
}
//获取随机字符串
function getRandomStr($length = 6){
    // 密码字符集，可任意添加你需要的字符
    $chars    = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ( $i = 0; $i < $length; $i++ )
    {
    // 这里提供两种字符获取方式
    // 第一种是使用 substr 截取$chars中的任意一位字符；
    // 第二种是取字符数组 $chars 的任意元素
    // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $password;
}